package mapping;

import executor.Executor;
import executor.impl.CachingExecutor;
import executor.impl.SimpleExecutor;
import handler.ResultSetHandler;
import handler.impl.DefaultParameterHandler;
import handler.ParameterHandler;
import handler.StatementHandler;
import handler.impl.DefaultResultSetHandler;
import handler.impl.PreparedStatementHandler;
import handler.impl.SimpleStatementHandler;

import javax.sql.DataSource;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2020-01-04 14:11
 * @notify mybatis全局配置类
 * @version 1.0
 */
public class Configuration {

    //是否使用二级缓存
    private boolean useCache = true;

    //封装MappedStatement对象集合

    private Map<String, MappedStatement> mappedStatements = new HashMap<String, MappedStatement>();
    //封装数据源
    private DataSource dataSource;

    //根据statementId获取MappedStatement对象
    public MappedStatement getMappedStatementById(String statementId) {
        return this.mappedStatements.get(statementId);
    }

    //添加MappedStatement对象
    public void addMappedStatement(String statementId, MappedStatement mappedStatement) {
        this.mappedStatements.put(statementId, mappedStatement);
    }

    //获取数据源
    public DataSource getDataSource() {
        return dataSource;
    }

    //设置数据源
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Executor newExecutor(String statementId,Object param)throws Exception {
        //通过配置文件，指定使用哪种Executor
        Executor executor = null;

        executor = new SimpleExecutor(this,statementId,param);

        if (useCache) {
            executor = new CachingExecutor(executor);
        }
        return executor;
    }

    public StatementHandler newStatementHandler(String statementType) {
        StatementHandler statementHandler = null;
        switch (statementType){
            case "prepared":
                statementHandler = new PreparedStatementHandler();
                break;
            case "statement":
              //  statementHandler = new SimpleStatementHandler();
                break;
        }
        return statementHandler;
    }

    public ParameterHandler newParameterHandler(){
        DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler();
        return defaultParameterHandler;
    }

    public ResultSetHandler newResultSetHandler(){
        return new DefaultResultSetHandler();
    }
}
